package com.meis.widget.photodrag;

import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

/**
 * Created by wenshi on 2018/5/18.
 * Description
 */
public class PhotoDragDelegate {
    private float mLastY;
    private boolean mIsBeingDragged;
    private int mTouchSlop;
    private OnPhotoDragListener mDragListener;

    public PhotoDragDelegate(Context context) {
        mTouchSlop = 22;
    }

    public PhotoDragDelegate setDragListener(OnPhotoDragListener listener) {
        mDragListener = listener;
        return this;
    }

    /**
     * 是否拦截事件
     * @param ev TouchEvent
     * @return boolean 是否拦截事件
     */
    public boolean onInterceptTouchEvent(TouchEvent ev) {
        if (mDragListener == null || mDragListener.isAnimationRunning() || mDragListener.getDragView() == null) {
            return false;
        }
        final int action = ev.getAction();
        float y = ev.getPointerScreenPosition(ev.getIndex()).getY();
        switch (action) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                mLastY = y;
                break;
            case TouchEvent.POINT_MOVE:
                final float yDiff = Math.abs(y - mLastY);
                mIsBeingDragged = yDiff > mTouchSlop;
                mLastY = y;
                break;
            case TouchEvent.PRIMARY_POINT_UP:
            case TouchEvent.CANCEL:
                mIsBeingDragged = false;
                break;
        }
        return mIsBeingDragged;
    }

    
    public void onTouchEvent(TouchEvent ev) {
        if (mDragListener == null) return;
        float y = ev.getPointerScreenPosition(ev.getIndex()).getY();
        switch (ev.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN:
                mLastY = y;
                break;
            case TouchEvent.POINT_MOVE: {
                float dy = y - mLastY;
                mDragListener.onDrag(dy);
                mLastY = y;
                break;
            }
            case TouchEvent.PRIMARY_POINT_UP:
            case TouchEvent.CANCEL:
                mIsBeingDragged = false;
                mDragListener.onRelease();
                break;
        }
    }
}
